{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "eager模式.ipynb",
      "provenance": [],
      "authorship_tag": "ABX9TyOij6sFcHpfyAjgr6JVYT5i",
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/sunyingjian/study-tensorflow/blob/master/eager%E6%A8%A1%E5%BC%8F.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "C0h1eAxF2s5D",
        "colab_type": "code",
        "outputId": "7cf7a927-9d3a-4d8e-98fe-1047c7e0e616",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 141
        }
      },
      "source": [
        "#引入Google drive文件\n",
        "import os\n",
        "from google.colab import drive\n",
        "drive.mount('/content/drive')\n",
        "path = \"/content/drive/My Drive/dataset\"\n",
        "os.chdir(path)\n",
        "os.listdir(path)"
      ],
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n",
            "\n",
            "Enter your authorization code:\n",
            "··········\n",
            "Mounted at /content/drive\n"
          ],
          "name": "stdout"
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['2_class', 'dc_2000']"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 1
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "_6idziTR00kB",
        "colab_type": "code",
        "outputId": "502e4f3e-34ab-47e9-c8a1-8ceb00767d90",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 141
        }
      },
      "source": [
        "#标准开场\n",
        "%tensorflow_version 2.x\n",
        "import tensorflow as tf\n",
        "print('tensorflow:',format(tf.__version__))\n",
        "tf.config.list_physical_devices('GPU')\n",
        "tf.test.is_gpu_available()\n",
        "import numpy as np\n",
        "from tensorflow import keras\n",
        "import glob\n",
        "from tensorflow.keras import layers\n",
        "import matplotlib.pyplot as plt\n",
        "%matplotlib inline\n",
        "tf.executing_eagerly()#判断是否处于eager模式"
      ],
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "TensorFlow 2.x selected.\n",
            "tensorflow: 2.1.0\n",
            "WARNING:tensorflow:From <ipython-input-2-aae37f9d17cd>:5: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.\n",
            "Instructions for updating:\n",
            "Use `tf.config.list_physical_devices('GPU')` instead.\n"
          ],
          "name": "stdout"
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "True"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 2
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8Ci2WeTG1TPz",
        "colab_type": "code",
        "outputId": "b8486464-4bae-4a33-baa0-36c6c6f403ab",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 52
        }
      },
      "source": [
        "#这里定义了一个x的向量\n",
        "#我们用numpy中矩阵乘法运算\n",
        "x=[[2,]]\n",
        "m=tf.matmul(x,x)\n",
        "print(m)\n",
        "m.numpy()"
      ],
      "execution_count": 3,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "tf.Tensor([[4]], shape=(1, 1), dtype=int32)\n"
          ],
          "name": "stdout"
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([[4]], dtype=int32)"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 3
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8tf9JroS2f8o",
        "colab_type": "code",
        "outputId": "2f6877b7-e8c4-4f9d-9a86-4340ac212694",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 190
        }
      },
      "source": [
        "#用python控制流实现tf运算\n",
        "num=tf.convert_to_tensor(10)\n",
        "#上面就是把一个值转换成一个向量对象\n",
        "num\n",
        "#输出这些值\n",
        "#这样的化下面输出的就是num中的对应的numpy的值\n",
        "for i in range(num.numpy()):\n",
        "  i=tf.constant(i)\n",
        "  if int(i%2)==0:\n",
        "#这里直接转换成了python对象\n",
        "    print('偶数')\n",
        "  else:\n",
        "    print('奇数')"
      ],
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "偶数\n",
            "奇数\n",
            "偶数\n",
            "奇数\n",
            "偶数\n",
            "奇数\n",
            "偶数\n",
            "奇数\n",
            "偶数\n",
            "奇数\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Lky6FLf04iqG",
        "colab_type": "code",
        "outputId": "b928faa7-5839-4abc-a2b9-fc12fbf34cc8",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        }
      },
      "source": [
        "#测试numpy中array\n",
        "d=np.array([[5,6],[7,8]])\n",
        "d\n",
        "g=tf.convert_to_tensor(10)\n",
        "g\n",
        "g.numpy()"
      ],
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "10"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 5
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "bUB-ooVO0caz",
        "colab_type": "code",
        "outputId": "d20788f3-3b9a-4a5c-a62d-745c73eda891",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        }
      },
      "source": [
        "#创建变量\n",
        "v=tf.Variable(0.0)\n",
        "v=v+1\n",
        "v.numpy()"
      ],
      "execution_count": 6,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "1.0"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 6
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "twybK-iC1VDl",
        "colab_type": "code",
        "outputId": "4b0866bf-4a7c-47f5-d1ad-d20447e3c10d",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        }
      },
      "source": [
        "v.shape"
      ],
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "TensorShape([])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 7
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "cC6Qp8GYDNHk",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "w=tf.Variable([[1.0]])\n",
        "with tf.GradientTape() as t:\n",
        "  #这里就是在这个通过记录一个过程来求导\n",
        "  #这个gradient这个函数会自动追踪这个变化\n",
        "  loss=w*w"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "GDpp_VfHEKRF",
        "colab_type": "code",
        "outputId": "0a8c4f1d-e54a-4b74-bf25-05d359953417",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        }
      },
      "source": [
        "grad = t.gradient(loss,w)\n",
        "grad"
      ],
      "execution_count": 9,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[2.]], dtype=float32)>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 9
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jzm4bHEMGaLc",
        "colab_type": "text"
      },
      "source": [
        "#常量求微分"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "bfo6xbJ9GZag",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "a=tf.constant(3.0)\n",
        "with tf.GradientTape(persistent=True) as t:\n",
        "  #因为他这里是一个常量所以添加一步\n",
        "  t.watch(a)\n",
        "  y=a*a\n",
        "  z=y*y"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lw-YEj-yWa8q",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "outputId": "1e93d464-403b-441f-c2b0-59e162f485b0"
      },
      "source": [
        "dy_da=t.gradient(y,a)\n",
        "#这就是计算y对a的微分\n",
        "#就是对y求导\n",
        "dy_da"
      ],
      "execution_count": 21,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(), dtype=float32, numpy=6.0>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 21
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Ue1Sw2YmZMSJ",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "outputId": "2a348d72-f215-4312-bc95-d998a4378db7"
      },
      "source": [
        "dz_da=t.gradient(z,a)\n",
        "dz_da"
      ],
      "execution_count": 23,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(), dtype=float32, numpy=108.0>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 23
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8PFEfd0GbpLX",
        "colab_type": "text"
      },
      "source": [
        "#自定义循环与训练"
      ]
    }
  ]
}